package xyz.gpgl.config.custom;

import common.util.base.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class MyDispatcherServlet extends DispatcherServlet {

	private static final  Map<String, String> urlForClass = new HashMap<String, String>();
	private static final  Map<String, String> urlForPath = new HashMap<String, String>();

	@Override
	protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(CommonUtil.isEmpty(urlForClass)){
			ServletContext servletContext = request.getSession().getServletContext();
			WebApplicationContext applicationContex = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
			RequestMappingHandlerMapping mapping = applicationContex.getBean(RequestMappingHandlerMapping.class);
			Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
			for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
				RequestMappingInfo info = m.getKey();
				HandlerMethod method = m.getValue();
				PatternsRequestCondition p = info.getPatternsCondition();
				for (String url : p.getPatterns()) {
					urlForClass.put( url , method.getMethod().getDeclaringClass().getName());
				}
			}
		}
		//拆解url
		String path =  request.getRequestURI();
		if(CommonUtil.isNotEmpty(urlForPath.get(path))){
			mv.setViewName(urlForPath.get(path));
		}else{
			if(path.split("[\\/]+").length == 4){
				String clazz = urlForClass.get(path);
				if(CommonUtil.isNotEmpty(clazz)){
					StringBuffer url = new StringBuffer();
					String[] paths = clazz.split("\\.");
					url.append("/").append(paths[2])
							.append("/").append(paths[3])
							.append("/").append(CommonUtil.dbForDBToFistLowercaseHump(paths[5].replace("Controller","")));
					if(mv.getViewName().indexOf("/")==-1){
						url.append("/");
					}
					url.append(mv.getViewName());
					mv.setViewName(url.toString());
				}
			}
		}
		super.render(mv, request, response);
	}
}
